<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Order extends Auth_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('order_mdl');
    }

    /**
     * 订单管理
     */
    public function index(){
        if($_SESSION['user']['status'] != 3){
            show_error('没有权限！');
        }
        $url = '';
        $this->db->start_cache();
        $sid = $this->input->get('sid');
        $sid = intval($sid);
        if(!empty($sid)){
            $this->db->where('status',$sid);
            $url .= 'sid='.$sid.'&';
        }
        $this->db->where('user_id',$_SESSION['user']['id']);
        $this->db->stop_cache();

        $this->load->library('pagination');

        if(!empty($url)){
            $url = '?'.substr($url,0,-1);
        }
        $config['base_url'] = site_url('order/index').$url;
        $config['total_rows'] = $this->order_mdl->get_count();
        $config['per_page'] = 10;
        $config['page_query_string'] = TRUE;
        $config['first_link'] = '首页';
        $config['last_link'] = '尾页';
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['anchor_class'] = 'current';

        $this->pagination->initialize($config);
        $data['page'] = $this->pagination->create_links();

        $per_page = $this->input->get('per_page');
        $this->db->limit($config['per_page'],intval($per_page));
        $this->db->order_by('update_time desc');
        $list = $this->order_mdl->select();
        $this->db->flush_cache();

        $status = $this->order_mdl->status;
        $this->load->model('parameters_mdl');
        foreach($list as $k => $v){
            $v['status'] = empty($v['status']) ? '0' : $v['status'];
            $list[$k]['status_name'] = $status[$v['status']];

            $this->db->where('id',$v['parameters_id']);
            $this->db->select('id,title,article_id');
            $list[$k]['par'] = $this->parameters_mdl->get_one();
        }

        //统计订单信息
        $count = array();
        foreach($status as $k => $v){
            $this->db->where('user_id',$_SESSION['user']['id']);
            $this->db->where('status',$k);
            $count[$k] = $this->order_mdl->get_count();
        }

        $data['list'] = $list;
        $data['sid'] = $sid;
        $data['status'] = $status;
        $data['count'] = $count;
        $data['all_count'] = $this->order_mdl->get_count();
        $this->_view('index',$data);
    }

    /**
     * 管理员订单管理
     */
    public function manage(){
        if($_SESSION['group'] > 2){
            show_error('没有权限打开此页面！');
        }

        $url = '';
        $this->db->start_cache();
        $sid = $this->input->get('sid');
        $sid = intval($sid);
        if(!empty($sid)){
            $this->db->where('status',$sid);
            $url .= 'sid='.$sid.'&';
        }
        $this->db->stop_cache();

        $this->load->library('pagination');

        if(!empty($url)){
            $url = '?'.substr($url,0,-1);
        }
        $config['base_url'] = site_url('order/manage').$url;
        $config['total_rows'] = $this->order_mdl->get_count();
        $config['per_page'] = 5;
        $config['page_query_string'] = TRUE;
        $config['first_link'] = '首页';
        $config['last_link'] = '尾页';
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['anchor_class'] = 'current';

        $this->pagination->initialize($config);
        $data['page'] = $this->pagination->create_links();

        $per_page = $this->input->get('per_page');
        $this->db->limit($config['per_page'],intval($per_page));
        $this->db->order_by('update_time desc');
        $list = $this->order_mdl->select();
        $this->db->flush_cache();

        $status = $this->order_mdl->status;
        $this->load->model('parameters_mdl');
        foreach($list as $k => $v){
            $v['status'] = empty($v['status']) ? '0' : $v['status'];
            $list[$k]['status_name'] = $status[$v['status']];

            $this->db->where('id',$v['parameters_id']);
            $this->db->select('id,title,article_id');
            $list[$k]['par'] = $this->parameters_mdl->get_one();
        }

        //统计订单信息
        $count = array();
        foreach($status as $k => $v){
            $this->db->where('status',$k);
            $count[$k] = $this->order_mdl->get_count();
        }

        $data['list'] = $list;
        $data['sid'] = $sid;
        $data['status'] = $status;
        $data['count'] = $count;
        $data['all_count'] = $this->order_mdl->get_count();
        $this->_view('manage',$data);
    }

    /**
     * 订单状态更改
     */
    public function processing(){
        if(!$this->input->is_ajax_request()){
            show_error('参数错误!');
        }

        if($_SESSION['user']['status'] == 3){
            show_error('没有权限！');
        }

        $post = $this->input->post();

        $status = intval($post['status']);
        $oid = intval($post['oid']);

        if($status <= 2 && $status>= 5){
            die('参数错误');
        }

        if(empty($oid)){
            die('参数错误！');
        }

        $this->db->where('id',$oid);
        $this->db->set('status',$status);
        $this->db->set('update_time',time());
        $res = $this->order_mdl->update();

        $this->db->where('id',$oid);
        $this->db->select('user_id');
        $order = $this->order_mdl->get_one();

        $sname = $this->order_mdl->status;
        $this->load->model('mess_mdl');
        $mess = sprintf("尊敬的用户您好，您订单号为%s的订单状态已经更改为“<span style='color:red'>%s</span>”,请及时处理。",$oid,$sname[$status]);
        $this->mess_mdl->send_message($mess,$order['user_id']);

        echo $res === TRUE ? 1 : '操作失败！';
    }

    /**
     * 用户订单签收
     */
    public function signing(){
        if($_SESSION['user']['status'] != 3){
            show_error('没有权限！');
        }
        if(!$this->input->is_ajax_request()){
            show_error('参数错误！');
        }

        $oid = $this->input->post('oid');
        $oid = intval($oid);

        $this->db->where('id',$oid);
        $this->db->where('user_id',$_SESSION['user']['id']);
        $this->db->where('status','4');

        $res = $this->order_mdl->get_one();

        if(empty($res)){
            die('该订单不存在！');
        }

        $this->db->set('status','5');
        $this->db->where('id',$oid);
        $this->db->set('update_time',time());
        $r = $this->order_mdl->update();

        echo $r === TRUE ? '1' : '操作失败！';

    }

    /**
     * 订单取消
     */
    public function quit_order(){
        if($_SESSION['user']['status'] == 3){
            show_error('没有权限！');
        }
        if(!$this->input->is_ajax_request()){
            show_error('参数错误！');
        }

        $oid = $this->input->post('oid');
        $mess = $this->input->post('mess');

        if(empty($mess)){
            die('请填写订单取消理由');
        }

        $this->db->where('id',intval($oid));
        $res = $this->order_mdl->get_one();

        if(empty($res)){
            die('该订单不存在');
        }

        if($res['status'] == 6){
            echo 1;
            exit;
        }

        $this->db->trans_start();

        $this->db->where('id',$res['id']);
        $this->db->set('mess',$mess);
        $this->db->set('status',6);
        $this->db->set('update_time',time());

        $r = $this->order_mdl->update();

        if($res['status'] > 1 && $r == TRUE){
            //Model
            $this->load->model('bill_mdl');
            $this->load->model('uinfo_mdl');

            //退还用户余额
            $data = array(
                'user_id' => $res['user_id'],
                'charges' => $res['price'],
                'remarks' => sprintf("订单号：“%s”，退款 “%s”",$res['id'],$res['price']),
                'update_time' => time()
            );
            $this->bill_mdl->create($data);

            $this->db->where('id',$res['user_id']);
            $this->db->set('money','money+'.$res['price'],FALSE);
            $this->uinfo_mdl->update();

            //发送电子邮件通知管理员
            $title = "订单取消通知，订单号：".$res['id'];
            $content = sprintf("订单号：%s，退款 \n",$res['id']);
            $content .= '处理人员:'.$_SESSION['uinfo']['name']." \n";
            $content .= '取消理由:'.$mess." \n";
            $content .= "--------------- \n";
            $content .= '联系人：'.$res['user_name'] . " \n";
            $content .= '联系电话：'.$res['user_phone'] . " \n";
            $content .= "--------------- \n";
            $content .= '取消时间：'.date('Y-m-d H:i:s') . " \n";
            $content .= $this->session->config->title;

            $this->send_admin($this->session->config->email,$title,$content);

            //发送电子邮件通知管理员
            $content = sprintf("订单号：%s，退款 \n",$res['id']);
            $content .= '处理人员:'.$_SESSION['uinfo']['name']." \n";
            $content .= '取消理由:'.$mess." \n";
            $content .= "--------------- \n";
            $content .= '联系人：'.$res['user_name'] . " \n";
            $content .= '联系电话：'.$res['user_phone'] . " \n";
            $content .= "--------------- \n";
            $content .= '退款金额:'.$res['price']. " \n" ;


            $this->db->where('id',$res['user_id']);
            $uinfo = $this->uinfo_mdl->get_one();

            $content .= '余额:'.$uinfo['money']. " \n" ;
            $content .= '取消时间：'.date('Y-m-d H:i:s') . " \n";
            $content .= $this->session->config->title;

            $this->send_admin($uinfo['email'],$title,$content);


        }
        $this->db->trans_complete();

        echo $r === TRUE ? 1 : '操作失败';
    }

    /**
     * 订单详情
     */
    public function oinfo(){

        $oid = $this->input->get('oid');
        if($_SESSION['user']['status'] == 3){
            $this->db->where('user_id',$_SESSION['user']['id']);
        }

        $this->db->where('id',intval($oid));
        $res = $this->order_mdl->get_one();

        if(empty($res)){
            show_error('该订单不存在');
        }

        //Model
        $this->load->model('uinfo_mdl');
        $this->load->model('parameters_mdl');
        $this->load->model('group_mdl');
        $this->load->model('users_mdl');
        $this->load->model('commission_mdl','comm_mdl');
        $this->load->model('prices_mdl');

        //查询用户详情
        $this->db->where('id',$res['user_id']);
        $res_uinfo = $this->uinfo_mdl->get_one();

        //查询项目详情
        $this->db->where('id',$res['parameters_id']);
        $res_par = $this->parameters_mdl->get_one();

        //查询用户权限
        $this->db->where('id',$res['user_id']);
        $this->db->select('id,group_id');
        $user = $this->users_mdl->get_one();

        $group = $this->group_mdl->select();
        $ugroup = array();
        foreach($group as $k => $v){
            if($v['id'] == $user['group_id']){
                $ugroup = $v;
                unset($group[$k]);
            }
        }
        //查询该订单佣金信息
        $this->db->where('order_id',$oid);
        $list_comm = $this->comm_mdl->select();
        //查询详细用户信息
        foreach($list_comm as $k => $v){
            $this->db->where('id',$v['user_id']);
            $this->db->select('name,phone,email');
            $list_comm[$k]['uinfo'] = $this->uinfo_mdl->get_one();

            $this->db->where('id',$v['user_id']);
            $this->db->select('id,username,group_id');
            $tmp_user = $this->users_mdl->get_one();
            $list_comm[$k]['user'] = $tmp_user;

            foreach($group as $key => $value){
                if($value['id'] == $tmp_user['group_id']){
                    $list_comm[$k]['group'] = $value;
                }
            }

        }
        //查询实际扣款信息
        $this->db->where('par_id',$res_par['id']);
        $this->db->where('group_id',$ugroup['id']);
        $price = $this->prices_mdl->get_one();

        $data = array(
            'res' => $res,
            'uinfo' => $res_uinfo,
            'status' => $this->order_mdl->status,
            'res_par' => $res_par,
            'handie' => $this->order_mdl->handie,
            'ugroup' => $ugroup,
            'list_comm' => $list_comm,
            'price' => $price
        );
        if($_SESSION['user']['status'] == 3){
            $this->_view('uinfo',$data);
        }else{
            $this->_view('oinfo',$data);
        }

    }


    /**
     * 用户创建订单
     */
    public function create(){
        if($_SESSION['user']['status'] != 3){
            show_error('没有权限！');
        }

        if(!$this->input->is_ajax_request()){
            show_error('参数错误！');
        }

        $pid = $this->input->post('pid');
        $pid = intval($pid);

        //查询项目属性信息
        $this->load->model('parameters_mdl');
        $this->db->where('id',$pid);
        $this->db->where('status',1);
        $res_par = $this->parameters_mdl->get_one();

        //查询项目信息
        $this->load->model('project_mdl');
        $this->db->where('id',$res_par['project_id']);
        $project = $this->project_mdl->get_one();

        if(empty($res_par)){
            die('该项目不存在，或者已经被下架，请重新选择！');
        }
        //加入订单表
        $mess = sprintf('购买了“ %s - %s ”，积分：%s ',$project['title'],$res_par['title'],$res_par['price']);
        $data = array(
            'user_id' => $_SESSION['user']['id'],
            'parameters_id' => $res_par['id'],
            'price' => $res_par['price'],
            'remarks' => $mess,
            'status' => '1',
            'create_time' => $_SERVER['REQUEST_TIME'],
            'update_time' => $_SERVER['REQUEST_TIME'],
        );
        $order_id = $this->order_mdl->create($data);

        echo empty($order_id) ? '操作失败！' : $order_id;

    }

    /**
     * 订单修改
     */
    public function update(){
        if($_SESSION['user']['status'] != 3){
            show_error('没有权限！');
        }

        $oid = $this->input->get('oid');

        $this->db->where('id',$oid);
        $this->db->where('user_id',$_SESSION['user']['id']);
        $this->db->where('status',1);
        $res = $this->order_mdl->get_one();

        if(empty($res)){
            show_error('该订单不存在!');
        }

        $this->load->model('parameters_mdl');
        $this->db->where('id',$res['parameters_id']);
        $res_par = $this->parameters_mdl->get_one();

        if($res_par['status'] == 2 || empty($res_par)){
            $this->db->where('id',$oid);
            $this->order_mdl->update(array('status'=>5));
            show_error('该项目已经被下架，不能支付购买，请浏览其他项目');
        }
        //print_r($_SESSION);
        $this->_view('update',array(
            'res'=>$res,
            'res_par' => $res_par
        ));
    }

    /**
     * 用户订单提交
     * 付款（记录入用户账单）
     * 更新订单状态
     * 邮件发送通知
     */
    public function user_update(){
        if($_SESSION['user']['status'] != 3){
            show_error('没有权限！');
        }

        if(!$this->input->is_ajax_request()){
            show_error('参数错误！');
        }

        $post = $this->input->post();

        if(empty($post['user_name'])){
            die('联系人不能为空');
        }

        if(!preg_match("/^1[0-9]{10}$/",$post['user_phone'])){
            die('联系电话格式错误，请填写11位的手机号码');
        }
        //导入MODEL
        $this->load->model('uinfo_mdl');
        $this->load->model('parameters_mdl');
        $this->load->model('bill_mdl');
        $this->load->model('prices_mdl');
        $this->load->model('money_mdl');
        $this->load->model('mess_mdl');

        //查询订单
        $this->db->where('id',intval($post['oid']));
        $this->db->where('status',1);
        $res = $this->order_mdl->get_one();
        if(empty($res)){
            die('订单不存在或者已经提交');
        }

        //查询项目
        $this->db->where('id',$res['parameters_id']);
        $res_par = $this->parameters_mdl->get_one();

        //查询用户余额
        $this->db->where('id',$_SESSION['user']['id']);
        $uinfo = $this->uinfo_mdl->get_one();

        if($uinfo['money'] - $res['price'] < 0){
            die('积分余额不足，请联系管理员充值余额。');
        }

        //扣除余额
        $this->db->trans_start();
        if(!$this->uinfo_mdl->debit($res_par['price'],$res['remarks'])){
            die('数据错误，请联系管理员');
        }
        // $this->db->trans_complete();
        // exit;
        //查询实际结算价格
        $this->db->where('par_id',$res_par['id']);
        $this->db->where('group_id',$_SESSION['group']);
        $prices = $this->prices_mdl->get_one();
        //echo $this->db->last_query();

        //摘除实际扣款，将剩余款项存入
        $prices = empty($prices) ? $res_par['price'] : $prices['price'];

        //如果和默认价格不相等
        if($prices != $res_par['price']){
            $this->money_mdl->add_money($res['id'],$res_par['price'],$prices);
        }

        //管理员订单通知
        $amess = '尊敬的管理员您好，有一个新的订单诞生，请及时处理！';
        $this->mess_mdl->send_admin($amess);
        //用户本人通知
        $this->mess_mdl->send_message($res['remarks']);

        //更改用户订单状态
        $data_order = array(
            'status' => '2',
            'user_name' => $post['user_name'],
            'user_phone' => $post['user_phone'],
            'user_remarks' => $post['content']
        );
        $this->db->where('id',$res['id']);
        $this->order_mdl->update($data_order);

        $this->db->trans_complete();

        if($this->db->trans_status() === FALSE){
            die('订单提交失败，请刷新重试');
        }else{
            //邮件通知
            $title = "订单通知，用户新购入".$res_par['title'];
            $content = '购入项目：'.$res_par['title']." \n";
            $content .= "----------------- \n";
            $content .= $res['remarks']." \n";
            $content .= "----------------- \n\n";
            $content .= "备注： \n".$post['content']." \n\n";
            $content .= "----------------- \n";
            $content .= '联系人：'.$post['user_name']." \n";
            $content .= '联系电话:' . $post['user_phone']. " \n";
            $content .= "----------------- \n";
            $content .= '订单ID：'.$post['oid'] . " \n";
            $content .= '购买人帐号:'. $_SESSION['user']['username']. " \n";
            $content .= '真实姓名 :' .$_SESSION['uinfo']['name']." \n";
            $content .= '订单时间：'.date('Y-m-d H:i:s');

            $this->send_admin($this->session->config->email,$title,$content);

            echo 1;
        }
    }

    /**
     * 后台订单受理 ， 分配资金
     */
    public function acceptance(){

        if(!$this->input->is_ajax_request()){
            show_error('参数错误！');
        }
        if($_SESSION['user']['status'] == 3){
            die('没有权限！');
        }

        $oid = $this->input->post('oid');
        if(intval($oid) < 1){
            die('参数错误');
        }

        $this->load->model('commission_mdl','comm_mdl');
        $this->load->model('money_mdl');

        //提取佣金
        $this->db->trans_start();
        $res = $this->comm_mdl->set_comm($oid);

        if($res){
            //更改订单状态
            $this->db->where('id',$oid);
            $this->db->set('status','3');
            $this->order_mdl->update();
            //通知
            $this->mess_mdl->send_message("尊敬的用户，您好， 您的订单已经受理！",$res);
            //将用户列表资金改为可领取
            $this->db->set('status','1');
            $this->db->where('order_id',$oid);
            $this->money_mdl->update();
        }else{
            die('受理订单失败！');
        }
        $this->db->trans_complete();
        echo 1;
    }

    /**
     * 订单删除
     */
    public function delete(){
        if(!$this->input->is_ajax_request()){
            show_error('参数错误！');
        }
        if($_SESSION['group'] != 3){
            die('没有权限！');
        }

        $oid = $this->input->post('oid');
        $this->db->where('id',intval($oid));
        $this->db->where('status',1);
        $this->db->where('user_id',$_SESSION['user']['id']);

        $res = $this->order_mdl->get_one();

        if(empty($res)){
            die('该订单不能删除!');
        }

        $this->db->where('id',$oid);
        $res = $this->order_mdl->delete();

        echo $res === TRUE ? 1 : '操作失败！';

    }

    /**
     * 查看订单详情
     */
    public function show_remarks(){
        if($_SESSION['group'] == 3){
            $this->db->where('user_id',$_SESSION['user']['id']);
        }
        $oid = $this->input->get('oid');

        $this->db->where('id',intval($oid));
        $this->db->select('id,user_remarks');

        $res = $this->order_mdl->get_one();

        if(empty($res)){
            show_error('该订单不存在');
        }
        if(empty($res['user_remarks'])){
            $res['user_remarks'] = '该订单没有备注';
        }
        $this->load->view('weigt/show_remarks',$res);

    }

}

/* End of file Order.php */
/* Location: ./application/controllers/Order.php */